package com.yups.web;
import com.yups.model.Coach;
import com.yups.model.Service;
import com.yups.model.ServiceType;
import com.yups.service.ServiceService;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(urlPatterns = "/servlet/ServiceSaveAction")
@MultipartConfig
public class ServiceSaveAction extends HttpServlet {
	private ServiceService serviceService = new ServiceService();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String act = request.getParameter("act");
		if (act == null) {
			act = "list";
		}
		Service service = getServiceFromRequest(request);
		switch (act) {
			case "addSave":
				String msg = checkService(service);
				if (!"".equals(msg)) {
					request.setAttribute("act", "addSave");
					request.setAttribute("service", service);
					request.setAttribute("serviceTypes",
							serviceService.getServiceTypes());
					request.setAttribute("coaches", serviceService.getCoaches());
					forward(request, response, msg,
							"../WEB-INF/jsp/service/input.jsp");
					return;
				}
				if (serviceService.add(service)) {
					request.setAttribute("serviceTypes",
							serviceService.getServiceTypes());
					request.setAttribute("coaches", serviceService.getCoaches());
					forward(request, response, "保存成功",
							"ServiceAction?act=list");
				} else {
					request.setAttribute("act", "addSave");
					request.setAttribute("service", service);
					request.setAttribute("serviceTypes",
							serviceService.getServiceTypes());
					request.setAttribute("coaches", serviceService.getCoaches());
					forward(request, response, "保存失败",
							"../WEB-INF/jsp/service/input.jsp");
				}
				break;
			case "updateSave":
				msg = checkService(service);
				if (!"".equals(msg)) {
					request.setAttribute("act", "updateSave");
					request.setAttribute("service", service);
					request.setAttribute("serviceTypes",
							serviceService.getServiceTypes());
					request.setAttribute("coaches", serviceService.getCoaches());
					forward(request, response, msg,
							"../WEB-INF/jsp/service/input.jsp");
					return;
				}
				if (serviceService.update(service)) {
					forward(request, response, "保存成功",
							"ServiceAction?act=list");
				} else {
					request.setAttribute("act", "updateSave");
					request.setAttribute("service", service);
					request.setAttribute("serviceTypes",
							serviceService.getServiceTypes());
					request.setAttribute("coaches", serviceService.getCoaches());
					forward(request, response, "保存失败",
							"../WEB-INF/jsp/service/input.jsp");
				}
				break;
			default:
				int size = Integer.parseInt(getServletContext()
						.getInitParameter("pageSize"));
				int page = 1;
				String page1 = request.getParameter("page");
				if (page1 != null && page1.matches("\\d{1,9}")) {
					page = Integer.parseInt(page1);
				}
				request.setAttribute("page", page);
				request.setAttribute("pageCount", serviceService.getPageCount(size));
				forward(request, response, "services",
						serviceService.getServices(page,size),
						"../WEB-INF/jsp/service/list.jsp");
		}
	}

	private void forward(HttpServletRequest request, HttpServletResponse response,
			String key,Object value, String url) throws ServletException, IOException {
		request.setAttribute(key, value);
		request.getRequestDispatcher(url).forward(request, response);
	}

	private void forward(HttpServletRequest request, HttpServletResponse response,
						 String msg,String url) throws ServletException, IOException {
		request.setAttribute("msg", msg);
		request.getRequestDispatcher(url).forward(request, response);
	}

	private String checkService(Service service) {
		String msg = "";
       if(service.getSubject()==null ||
			   !service.getSubject().matches("\\S{1,5}")){
           return  "您输入的标题应该在1-5个字符。";
       }
		return msg;
	}

	private Service getServiceFromRequest(HttpServletRequest request)
			throws IOException, ServletException {
		Service service = new Service();
		String id = request.getParameter("id");
		if (id != null && id.matches("\\d{1,9}")) {
			service.setId(Integer.parseInt(id));
		}
		service.setSubject(request.getParameter("subject"));
		// 得到物理地址
		String uploadDir = getServletContext().getInitParameter("uploadDir");
		// 网址换成磁盘路径
		String realPath = getServletContext().getRealPath(uploadDir);
		File file = new File(realPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		Part coverpath = request.getPart("coverpath");
		if (coverpath != null && coverpath.getSize() > 0) {
			String submittedFileName = coverpath.getSubmittedFileName();
			String fileName = converFileName(submittedFileName);
			service.setCoverpath(fileName);
			coverpath.write(realPath + "\\" + fileName);
		}
		String price = request.getParameter("price");
		if (price != null && price.matches("\\d{1,9}")) {
			service.setPrice(Integer.parseInt(price));
		}
		service.setMessage(request.getParameter("message"));
		String serviceTypeId = request.getParameter("serviceTypeId");
		if (serviceTypeId != null && serviceTypeId.matches("\\d{1,9}")) {
			service.setServiceType(new ServiceType(Integer.parseInt(serviceTypeId)));
		}
		String coachId = request.getParameter("coachId");
		if (coachId != null && coachId.matches("\\d{1,9}")) {
			service.setCoach(new Coach(Integer.parseInt(coachId)));
		}
		service.setRecommend(request.getParameter("recommend"));
		service.setDetail(request.getParameter("detail"));
		service.setPhoto(request.getParameter("photo"));
		Part photo = request.getPart("photo");
		if (photo != null && photo.getSize() > 0) {
			String submittedFileName = photo.getSubmittedFileName();
			String fileName = converFileName(submittedFileName);
			service.setPhoto(fileName);
			photo.write(realPath + "\\" + fileName);
		}
		return service;
	}

	private String converFileName(String submittedFileName) {
		SimpleDateFormat simpleFormatter =
				new SimpleDateFormat("-yyyyMMddhhmmss");
		String temp = simpleFormatter.format(new Date());
		int pos = submittedFileName.lastIndexOf(".");
		return submittedFileName.substring(0, pos) + temp
				+ submittedFileName.substring(pos);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
